<?php
namespace Admin\Controller;

use Think\Controller;

class BaseController extends Controller
{
    /**
     * +----------------------------------------------------------
     * 初始化
     * 如果 继承本类的类自身也需要初始化那么需要在使用本继承类的类里使用parent::_initialize();
     * +----------------------------------------------------------
     */
    public function _initialize()
    {
        if (!session('?Admin')) {
            //dump(session('Admin'));
            redirect(U('Common/Login', '', ''));
        }
        $this->assign('NickName', session('Admin')['NickName']);
        $this->assign('menu', $this->show_menu());
    }

    /*
     * basic index
     */
    public function index($title)
    {
        $this->assign('title', $title);
        layout('tablelayout');
        $this->display();
    }

    /*
     * 获取列表数据
     */
    public function GetData($data)
    {
        $draw = I('draw');

        //条件过滤后记录数 必要
        $recordsFiltered = $data['recordsFiltered'];
        //表的总记录数 必要
        $recordsTotal = $data['recordsTotal'];

        echo json_encode(array(
            "draw" => intval($draw),
            "recordsTotal" => intval($recordsTotal),
            "recordsFiltered" => intval($recordsFiltered),
            "data" => $data['data']
        ), JSON_UNESCAPED_UNICODE);
    }

    /**
     * 显示菜单
     * @return mixed
     */
    private function show_menu()
    {
        $menu = C('admin_big_menu');
        $sub = C('admin_sub_menu');

        foreach ($menu as $index => $name) {
            $menu[$index]['menu_class'] = '';
            $menu_sub = array();
            foreach ($sub[$index] as $url => $subname) {
                $created_sub['url'] = $url;
                $created_sub['subname'] = $subname;
                $created_sub['sub_class'] = '';
                if ($this->getCheckUrl() == $url) {
                    $menu[$index]['menu_class'] = ' class="active opened active"';
                    $created_sub['sub_class'] = ' class="active"';
                }
                array_push($menu_sub, $created_sub);
            }
            $menu[$index]['sub'] = $menu_sub;
        }

        return $menu;
    }

    /**
     * 得到菜单高亮检查所用的url
     * @return string
     */
    private function getCheckUrl()
    {
        $url = CONTROLLER_NAME . '/' . ACTION_NAME;

        if ('CourseRelation' == ACTION_NAME && 'Training' == CONTROLLER_NAME) {
            $url = 'Training/index';
        }
        if ('Add' == ACTION_NAME && 'Pages' == CONTROLLER_NAME) {
            $url = 'Pages/index';
        }

        return $url;
    }
}